/*
 * Copyright (C) 2010 Marc Reichelt
 * 
 * Work derived from Workspace.java of the Launcher application
 *  see http://android.git.kernel.org/?p=platform/packages/apps/Launcher.git
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package vn.com.tiz.DocumentZ.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

public class VerticalViewSwitcher extends ViewGroup {

	public static interface OnScreenSwitchListener {	
		void onScreenSwitched(int screen);
	}
	
	

	private static final int SNAP_VELOCITY = 1000;
	private static final int INVALID_SCREEN = -1;

	private Scroller mScroller;
	private VelocityTracker mVelocityTracker;

	private final static int TOUCH_STATE_REST = 0;
	private final static int TOUCH_STATE_SCROLLING = 1;

	private int mTouchState = TOUCH_STATE_REST;

	private float mLastMotionY;
	
	private float mLastMotionX;
	private int mTouchSlop;
	private int mMaximumVelocity;
	private int mCurrentScreen;
	private int mNextScreen = INVALID_SCREEN;

	private boolean mFirstLayout = true;
	
	public boolean isScrolling = false;

	private OnScreenSwitchListener mOnScreenSwitchListener;

	public VerticalViewSwitcher(Context context) {
		super(context);
		init();
	}

	public VerticalViewSwitcher(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		mScroller = new Scroller(getContext());

		final ViewConfiguration configuration = ViewConfiguration.get(getContext());
		mTouchSlop = configuration.getScaledTouchSlop();
		//Log.d("TrungTT","TouchSlop:"+mTouchSlop);
		mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		final int width = MeasureSpec.getSize(widthMeasureSpec);
		final int height = MeasureSpec.getSize(heightMeasureSpec);
		final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		if (widthMode != MeasureSpec.EXACTLY) {
			throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode.");
		}

		final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		if (heightMode != MeasureSpec.EXACTLY) {
			throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode.");
		}

		// The children are given the same width and height as the workspace
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}

		if (mFirstLayout) {
			scrollTo( 0,mCurrentScreen * height);
			mFirstLayout = false;
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		//int childLeft = 0;
		int viewTop = 0;
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			final View child = getChildAt(i);
			
			if (child.getVisibility() != View.GONE) {
				
				final int childHeight = child.getMeasuredHeight();
				child.layout(0, viewTop,child.getMeasuredWidth(), viewTop + childHeight);
				viewTop += childHeight;
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		
		//return true;
		
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		
		mVelocityTracker.addMovement(ev);
		final int action = ev.getAction();
		final float y = ev.getY();

		switch (action) {
		case MotionEvent.ACTION_DOWN:		
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}		
			mLastMotionY = y;
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
			break;
		case MotionEvent.ACTION_MOVE:
			final int yDiff = (int) Math.abs(y - mLastMotionY);
			
			boolean yMoved = yDiff > mTouchSlop;
			if (yMoved) {
				// Scroll if the user moved far enough along the X axis
				mTouchState = TOUCH_STATE_SCROLLING;
			}else
			{
				//Log.d("trungtt","not y move");
				//return true;
			}
			
			if (mTouchState == TOUCH_STATE_SCROLLING) {			
				//mLastMotionY = y;
				final int deltaY = (int) (mLastMotionY - y);
				mLastMotionY = y;
				final int scrollY = getScrollY();
				if (deltaY < 0) {
					if (scrollY > 0) {
						
						scrollBy(0,Math.max(-scrollY, deltaY));
						//Log.d("TrungTT", "scroll down,scrollY="+scrollY+"deltaY="+deltaY);
					}
				} else if (deltaY > 0) {
					final int availableToScroll = getChildAt(getChildCount() - 1 ).getBottom() - scrollY - getHeight();
					//scrollBy( 0,deltaY);
					if (availableToScroll > 0) {
						scrollBy( 0,Math.min(availableToScroll, deltaY));
						//Log.d("trungtt", "scroll up");
					}
				}
			}
			
			//Log.d("trungtt", "Mouse Move : x = "+x);
			break;

		case MotionEvent.ACTION_UP:
			if (mTouchState == TOUCH_STATE_SCROLLING) {
				final VelocityTracker velocityTracker = mVelocityTracker;
				velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
				//int velocityX = (int) velocityTracker.getXVelocity();

				int velocityY = (int) velocityTracker.getYVelocity();
				if (velocityY > SNAP_VELOCITY && mCurrentScreen > 0) {
					// Fling hard enough to move left
					snapToScreen(mCurrentScreen - 1);
					//Log.d("trungtt","fling to left");
				} else if (velocityY < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
					// Fling hard enough to move right
					snapToScreen(mCurrentScreen + 1);
				} else {
					snapToDestination();
					//Log.d("trungtt","destination");
				}

				if (mVelocityTracker != null) {
					mVelocityTracker.recycle();
					mVelocityTracker = null;
				}
			}

			mTouchState = TOUCH_STATE_REST;

			//Log.d("trungtt", "Mouse Up : x = "+x);
			break;
		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
			//Log.d("trungtt", "Cancel : x = "+x);
		}
		

		//return super.onTouchEvent(ev);
		return true;
	}
	

	public boolean hasStopAnimatio()
	{
		return mScroller.isFinished();
	}
	
	private void snapToDestination() {
		//final int screenWidth = getWidth();
		
		final int screenHeight = getHeight();
		final int whichScreen = (getScrollY() + (screenHeight / 2)) / screenHeight;

		snapToScreen(whichScreen);
	}

	public void snapToScreen(int whichScreen) {
		if (!mScroller.isFinished())
			return;

		isScrolling = true;
		whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
		mNextScreen = whichScreen;

		final int newY = whichScreen * getHeight();
		final int delta = newY - getScrollY();
		//mScroller.startScroll(0, getScrollY(), 0, 1000);
		mScroller.startScroll(0, getScrollY(), 0, delta, 1000);
		//mScroller.startScroll(0, getScrollY(), 0, delta, Math.abs(delta) * 2);
		invalidate();
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		} else if (mNextScreen != INVALID_SCREEN) {
			mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1));

			// notify observer about screen change
			if (mOnScreenSwitchListener != null)
				mOnScreenSwitchListener.onScreenSwitched(mCurrentScreen);

			mNextScreen = INVALID_SCREEN;
		}
	}


	public int getCurrentScreen() {
		return mCurrentScreen;
	}


	public void setCurrentScreen(int currentScreen) {
		mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1));
		scrollTo(mCurrentScreen * getHeight(), 0);
		invalidate();
	}

	
	public void setOnScreenSwitchListener(OnScreenSwitchListener onScreenSwitchListener) {
		mOnScreenSwitchListener = onScreenSwitchListener;
	}

}
